package manage.commons.tags;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 标签抽象类，添加其他的自定义标签都继承这个类
 * 
 * @author dongji
 * @since 2012-9-6 下午03:49:12
 */
public abstract class AbstractTag extends TagSupport {

	private static final long serialVersionUID = 3234375809496738889L;
	protected WebApplicationContext spring;

	@Override
	public int doStartTag() throws JspException {
		ServletContext servletContext = pageContext.getServletContext();
		spring = WebApplicationContextUtils
				.getRequiredWebApplicationContext(servletContext);
		// 根据名字自动装配这个类
		spring.getAutowireCapableBeanFactory().autowireBeanProperties(this,
				AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
		return super.doStartTag();
	}

	@Override
	public int doEndTag() throws JspException {
		String content = doTag();
		try {
			pageContext.getOut().write(content);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doEndTag();
	}

	protected abstract String doTag();

}
